import { createRouter, createWebHistory } from 'vue-router'
import { h } from 'vue'
import ACCESS_ENUM from '@/router/AccessEnum.ts'
import { HomeOutlined, SettingOutlined } from '@ant-design/icons-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import checkRole from '@/router/CheckAccess.ts'
import AddPicturePage from '@/pages/picture/AddPicturePage.vue'
import AddPictureBatchPage from '@/pages/picture/AddPictureBatchPage.vue'
import spaceManagePage from '@/pages/admin/space/spaceManagePage.vue'
import AddSpacePage from '@/pages/space/AddSpacePage.vue'
import MySpacePage from '@/pages/space/MySpacePage.vue'
import SpaceDetailPage from '@/pages/space/SpaceDetailPage.vue'
import SearchPicturePage from '@/pages/picture/SearchPicturePage.vue'
import SpaceAnalyzePage from '@/pages/space/SpaceAnalyzePage.vue'
import SpaceUserManagePage from '@/pages/space/SpaceUserManagePage.vue'
// 动态导入组件
const HomePage = () => import('@/pages/HomePage.vue')
const UserLoginPage = () => import('@/pages/user/UserLoginPage.vue')
const UserRegisterPage = () => import('@/pages/user/UserRegisterPage.vue')
const UserManagePage = () => import('@/pages/admin/user/UserManagePage.vue')
const PictureManage = () => import('@/pages/admin/picture/PictureManagePage.vue')
const PictureDetailPage = () => import('@/pages/picture/PictureDetailPage.vue')
const AboutView = () => import('@/views/AboutView.vue')

// 默认的 meta 信息
const defaultMeta = {
  showMenu: true,
}

/**
 * 路由配置数组
 * 目前这个配置的弊端是,一级路由的 name 和 path 必须是唯一的,同时必须配置 showMenu: true/false表示在菜单中显示/隐藏
 */
export const myRouters = [
  {
    path: '/',
    redirect: '/home', // 根路径重定向到主页
  },
  {
    path: '/home',
    name: '主页',
    component: HomePage,
    meta: {
      ...defaultMeta,
      icon: () => h(HomeOutlined),
      access: ACCESS_ENUM.GUEST, // 所有人可以访问
    },
  },
  {
    path: '/admin/user/userManage',
    name: '用户管理',
    component: UserManagePage,
    meta: {
      ...defaultMeta,
      title: '用户管理',
      access: ACCESS_ENUM.ADMIN,
    },
  },
  {
    path: '/admin/picture/pictureManage',
    name: '图片管理',
    component: PictureManage,
    meta: {
      ...defaultMeta,
      title: '图片管理',
      access: ACCESS_ENUM.ADMIN,
    },
  },
  {
    path: '/admin/spaceManage',
    name: '空间管理',
    component: spaceManagePage,
    meta: {
      ...defaultMeta,
      title: '空间管理',
      access: ACCESS_ENUM.ADMIN,
    },
  },
  {
    path: '/picture/:id',
    name: '图片详情',
    component: PictureDetailPage,
    props: true, // 将路由参数传递给组件,这里就是将路径上的id传递给组件当中
    meta: {
      showMenu: false,
      title: '图片详情',
      access: ACCESS_ENUM.GUEST,
    },
  },
  {
    path: '/add_picture',
    name: '添加图片',
    component: AddPicturePage,
    meta: {
      ...defaultMeta,
      title: '添加图片',
      access: ACCESS_ENUM.USER,
    },
  },
  {
    path: '/add_picture/batch',
    name: '批量创建图片',
    component: AddPictureBatchPage,
    meta: {
      showMenu: false,
      title: '批量创建图片',
      access: ACCESS_ENUM.ADMIN,
    },
  },
  {
    path: '/add_space',
    name: '创建空间',
    component: AddSpacePage,
    meta: {
      showMenu: false,
      title: '创建空间',
      access: ACCESS_ENUM.USER,
    },
  },
  {
    path: '/my_space',
    name: '我的空间',
    component: MySpacePage,
    meta: {
      showMenu: false,
      title: '我的空间',
      access: ACCESS_ENUM.USER,
    },
  },
  {
    path: '/space/:id',
    name: '空间详情',
    component: SpaceDetailPage,
    meta: {
      showMenu: false,
      title: '空间详情',
      access: ACCESS_ENUM.USER,
    },
    // props: true, 表示将路由参数传递给组件,这里就是将路径上的id传递给组件
    props: true,
  },
  {
    path: '/spaceUserManage/:id',
    name: '空间成员管理',
    component: SpaceUserManagePage,
    meta: {
      showMenu: false,
      title: '空间成员管理',
      access: ACCESS_ENUM.USER,
    },
    // props: true, 表示将路由参数传递给组件,这里就是将路径上的id传递给组件
    props: true,
  },
  {
    path: '/space_analyze',
    name: '空间分析',
    component: SpaceAnalyzePage,
    meta: {
      showMenu: false,
      title: '空间分析',
      access: ACCESS_ENUM.USER,
    },
    // // props: true, 表示将路由参数传递给组件,这里就是将路径上的id传递给组件
    // props: true,
  },
  {
    path: '/search_picture',
    name: '以图搜图',
    component: SearchPicturePage,
    meta: {
      showMenu: false,
      title: '以图搜图',
      access: ACCESS_ENUM.USER,
    },
    // props: true, 表示将路由参数传递给组件,这里就是将路径上的id传递给组件
    props: true,
  },
  {
    path: '/about',
    name: '关于',
    component: AboutView,
    meta: {
      ...defaultMeta,
      icon: () => h(SettingOutlined),
      access: ACCESS_ENUM.USER, // 需要登录后访问
    },
    // 注意，以 / 开头的嵌套路径将被视为根路径。 嵌套的不需要 添加 /
    children: [
      {
        path: 'user',
        name: '关于信息',
        component: AboutView,
        meta: {
          ...defaultMeta,
          access: ACCESS_ENUM.USER,
        },
      },
      {
        path: 'user2',
        name: '关于信息2',
        component: AboutView,
        meta: {
          ...defaultMeta,
          access: ACCESS_ENUM.ADMIN,
        },
      },
    ],
  },
  {
    path: '/login',
    name: '登录',
    component: UserLoginPage,
    meta: {
      showMenu: false,
    },
  },
  {
    path: '/register',
    name: '注册',
    component: UserRegisterPage,
    meta: {
      showMenu: false,
    },
  },
  {
    path: '/noAuth',
    name: '无权限',
    component: () => import('@/pages/NoAuth.vue'),
    meta: {
      showMenu: false,
    },
  },
]

export const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: myRouters,
})

// 全局前置守卫
// https://router.vuejs.org/zh/guide/advanced/navigation-guards.html
router.beforeEach(async (to, from) => {
  const loginUserStore = useLoginUserStore()

  // 如果目标页面是登录页面，则清除登录状态
  if (to.path === '/login' || to.path === '/register') {
    await loginUserStore.logout() // 假设你有一个 logout 方法来清除登录状态
    // undefined 或返回 true，则导航是有效的，并调用下一个导航守卫
    return true
  }

  let loginUser = loginUserStore.loginUser
  console.log('登陆用户信息', loginUser)

  // 如果用户未登录
  if (!loginUser || !loginUser.userRole) {
    console.log('浏览器输入URL-用户未登录', to.fullPath)
    // 如果目标页面没有 access 属性，或者 access 属性为 guest，则允许访问
    if (to.meta?.access && to.meta.access !== ACCESS_ENUM.GUEST) {
      // 避免从登录页面再次重定向到登录页面
      return `/login?redirect=${encodeURIComponent(to.fullPath)}`
    }
  } else {
    // 用户已登录，检查是否有足够的权限访问目标页面
    const needAccess = to.meta?.access ?? ACCESS_ENUM.GUEST
    if (!checkRole(loginUser, needAccess, to.fullPath)) {
      // return 可以是路由对象，也可以是字符串
      return { path: '/noAuth' }
    }
  }
  // 什么都不返回，则导航是有效的，并调用下一个导航守卫
})
